<?php

namespace app\common\controller;

use app\BaseController;
use think\facade\Cache;
use function think\isMobile;

class Helper extends BaseController
{

    public function getCode()
    {
        $result = [
            "status" => "no",
            "data" => [],
            "msg" => "查找失败"
        ];
        $request = $this->request;
        $mobile = $request->param('mobile', '');
        if (empty($mobile)) {
            $result['msg'] = '请输入手机号码';
            return json($result);
        }
        if (!isMobileNumber($mobile)) {
            $result['msg'] = '请输入正确的手机号码';
            return json($result);
        }
        $result = $this->sendMobile($mobile, 'verify');
        if ($result['result']['Code'] == 'OK') {
            $result["status"] = 'ok';
            $result["data"] = $result['code'];
            $result["msg"] = '短信发送成功';
        } else {
            $result['data'] = $result;
            $result['msg'] = '短信发送失败';
        }
        return json($result);
    }

    public function sendMobile($mobile, $msgType, $code = '', $data = [])
    {
        $sendMsg = new \AliyunSms();

        if (!$code) {
            $code = rand(100000, 999999);
        }
        $cacheKey = $mobile . $msgType;
        $cacheInfo = Cache::get($cacheKey);
        if ($cacheInfo) {
            return ["msg" => "短信已发送"];
        }
        $sendData = array(
            'PhoneNumbers' => $mobile,
            'templateParam' => array(
                'code' => $code
            )
        );
        $sendData["templateParam"] = array_merge($sendData["templateParam"], $data);
        $sendResult = $sendMsg->sendSms($sendData, $msgType);
        $sendResult = $sendResult->toArray();
        if ($sendResult['Code'] == 'OK') {
            Cache::set($cacheKey, $code, 5);
        }
        return ['result' => $sendResult, 'code' => $code];
    }

    public function uploadFile()
    {

    }
}
